export type ToolbarPopupType = "select" | "popover" | "dropdown";

export interface ToolbarPopupInstance {
  type: ToolbarPopupType;
  instance: HTMLElement | any;
  close: () => void;
  isOpen: () => boolean;
}

/**
 * 关闭事件名称
 */
export const CLOSE_ALL_TOOLBAR_POPUPS_EVENT = "close-all-toolbar-popups";

/**
 * 关闭事件详情接口
 */
export interface CloseAllToolbarPopupsEventDetail {
  currentInstance?: HTMLElement | any;
  currentType?: ToolbarPopupType;
  excludeTypes?: ToolbarPopupType[];
}

/**
 * 触发关闭所有工具栏弹窗的事件
 * @param currentInstance 当前实例（不会被关闭）
 * @param currentType 当前弹窗类型
 * @param excludeTypes 需要排除的类型（不会关闭这些类型）
 */
export function closeAllToolbarPopups(
  currentInstance?: HTMLElement | any,
  currentType?: ToolbarPopupType,
  excludeTypes?: ToolbarPopupType[]
) {
  const event = new CustomEvent<CloseAllToolbarPopupsEventDetail>(
    CLOSE_ALL_TOOLBAR_POPUPS_EVENT,
    {
      detail: {
        currentInstance,
        currentType,
        excludeTypes,
      },
    }
  );
  document.dispatchEvent(event);
}

/**
 * 监听关闭所有工具栏弹窗的事件
 * @param handler 处理函数
 * @returns 清理函数
 */
export function onCloseAllToolbarPopups(
  handler: (event: CustomEvent<CloseAllToolbarPopupsEventDetail>) => void
) {
  const eventHandler = handler as EventListener;
  document.addEventListener(CLOSE_ALL_TOOLBAR_POPUPS_EVENT, eventHandler);
  return () => {
    document.removeEventListener(CLOSE_ALL_TOOLBAR_POPUPS_EVENT, eventHandler);
  };
}
